const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')

const externals = {
	vue: 'Vue',
	axios: 'axios',
	vuex: 'Vuex',
	'vue-router': 'VueRouter',
	'element-plus': 'ElementPlus',
	'better-scroll': 'BetterScroll',
};
const cdn = {
	css: [
		'https://cdn.bootcdn.net/ajax/libs/normalize/8.0.1/normalize.min.css',
		'https://unpkg.com/browse/element-plus@1.2.0-beta.6/theme-chalk/index.css'
	],
	js: [
		'https://cdn.bootcdn.net/ajax/libs/vue/3.2.10/vue.global.min.js',
		'https://cdn.bootcdn.net/ajax/libs/vue-router/4.0.0/vue-router.global.min.js',
		'https://cdn.bootcdn.net/ajax/libs/vuex/4.0.2/vuex.global.min.js',
		'https://cdn.bootcdn.net/ajax/libs/axios/0.21.4/axios.min.js',
		'https://unpkg.com/element-plus@1.2.0-beta.6/dist/index.full.min.js',
		'https://unpkg.com/browse/element-plus@1.2.0-beta.6/lib/locale/lang/zh-cn.js',
		'https://cdn.bootcdn.net/ajax/libs/better-scroll/2.4.2/better-scroll.min.js',
	]
}
module.exports = {
	chainWebpack: (config) => {
		config.optimization.minimize(true);
		 config.plugin('uglifyjs-webpack-plugin').use(
			new UglifyJsPlugin({
				test: /\.js(\?.*)?$/i,
			})
		 );
		config.plugin('compressionPlugin').use(
			new CompressionWebpackPlugin({
				filename: "[path][base].gz",
				algorithm: "gzip",
				test: /\.js$|\.css$|\.html$/,
				threshold: 10240,
				minRatio: 0.8,
			})
		);
		// 配置，将当前页定义的cdn值传到主页面（index.html）
		config.plugin('html').tap(args => {
			// 这里我是除本地环境，其余均使用CDN，可自己选择是否配置
			args[0].cdn = cdn;
			return args;
		});
		config.plugins.delete('prefetch'); //默认开启prefetch(预先加载模块)，提前获取用户未来可能会访问的内容 在首屏会把这十几个路由文件，都一口气下载了 所以我们要关闭这个功能模块
		// if (process.env.NODE_ENV !== 'development') {
		// 对超过10kb的文件gzip压缩
		config.plugin('compressionPlugin').use(
			new CompressionWebpackPlugin({
				test: /\.(js|css|html)$/, // 匹配文件名
				threshold: 10240,
			})
		);
	},
	configureWebpack: {
		externals: {
			'vue': 'Vue',
			'vuex': 'Vuex',
			'vue-router': 'VueRouter',
			'axios': 'axios',
			'element-ui': 'ELEMENT',
		}
	}
}
